<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>

    <el-tree
      style="margin: 20px 0"
      ref="tree"
      node-key="id"
      :props="props"
      show-checkbox
      :data="allPermissions"
    >
    </el-tree>
    <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    <el-button @click="$router.replace({ name: 'Role' })">取消</el-button>
  </div>
</template>

<script>
import permissionApi from "@/api/acl/permission";
export default {
  name: "roleAuth",

  data() {
    return {
      loading: false, // 用来标识是否正在保存请求中的标识, 防止重复提交
      allPermissions: [], // 所有数据
      props: {
        label: "name",
        children: "children",
      },
    };
  },
  created() {
    this.init();
  },

  methods: {
    // 初始化
    init() {
      const roleId = this.$route.params.id;
      this.getPermissions(roleId);
    },

    // 获取指定角色的权限列表
    getPermissions(roleId) {
      permissionApi.toAssign(roleId).then((result) => {
        // console.log(result);
        const allPermissions = result.data.children;
        this.allPermissions = allPermissions;
        // 获取所有选中id列表
        const checkedIds = this.getCheckedIds(allPermissions);
        console.log("获取所有选中id列表", checkedIds);
        // 选中
        this.$refs.tree.setCheckedKeys(checkedIds);
      });
    },

    // 得到所有选中的id列表
    getCheckedIds(auths, initArr = []) {
      return auths.reduce((pre, item) => {
        if (item.select && item.level === 4) {
          pre.push(item.id);
        } else if (item.children) {
          // 递归
          this.getCheckedIds(item.children, initArr);
        }
        return pre;
      }, initArr);
    },

    // 保存按钮
    save() {
      var ids = this.$refs.tree.getCheckedKeys().join(",");
      console.log(this.$refs.tree.getCheckedKeys());

      this.loading = true;
      permissionApi.doAssign(this.$route.params.id, ids).then((result) => {
        this.loading = false;
        this.$message.success(result.$message || "分配权限成功");
      });
      //   必须在跳转前获取  跳转后this获取不到正确数据
      //   const roleName = this.$route.query.roleName;
      //   const roles = this.$store.getters.roles;
      this.$router.replace("/limits/role");
    },
  },
};
</script>
